<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 6/30/17
 * Time: 4:02 PM
 */
declare(strict_types=1);


namespace application\module\admin\addon\rbca\model;


use application\module\admin\addon\model\AddonModel;

/**
 * Class ReflectModel
 *
 * @property string $module         模块名称
 * @property string $controller     控制器名称
 * @property string $method         方法名称
 * @property string $path           "模块+控制器+方法"
 * @property string $update_time    更新时间
 * @property string $add_time       添加时间
 * @property string $comment        备注
 *
 * @package application\module\admin\addon\rbca\model
 */
class ReflectModel extends AddonModel
{


    protected function tableName()
    {
        return 'reflect';
    }

    protected function struct(): string
    {
        return "  `id` int(11) NOT NULL AUTO_INCREMENT,
  `module` varchar(255) NOT NULL DEFAULT '' COMMENT '模块名称',
  `controller` varchar(255) NOT NULL COMMENT '控制器名称',
  `method` varchar(255) NOT NULL COMMENT '方法名称',
  `path` varchar(255) NOT NULL COMMENT '“模块+控制器+方法”',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
  `add_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `comment` varchar(255) NOT NULL DEFAULT '' COMMENT '备注',
  PRIMARY KEY (`id`),
  UNIQUE KEY `path` (`path`)";
    }

    public function __construct($id = null)
    {
        if ($id) {
            if (is_numeric($id)) {
                parent::__construct($id);
            } else {
                $data = $this->where(['path' => $id])->find();
                if ($data) {
                    $this->id = $data['id'];
                    $this->data = $data;
                }
            }
        } else {
            parent::__construct();
        }
    }

    /**
     * 获取列表，对于路径加入了权限管理的，设置aid
     * @return array
     */
    public function getlist(): array
    {
        $prefix = $this->tablePrefix();
        $table = $this->getTable();
        $res = $this->query("SELECT r.*,IFNULL(a.id,0) as aid FROM {$table} r 
LEFT OUTER JOIN {$prefix}auth_access a on a.`value` = r.path");
        return $res;
    }

    public function has(string $path): bool
    {
        return $this->where(['path' => $path])->count() > 0;

    }


    public function save($justInsert = false): bool
    {
        if ($justInsert and $this->has($this->path)) {
            $this->error = "path '{$this->path}' exist";
            return false;
        }
        return parent::save($justInsert);
    }
}